package com.gict.antifraudback.aspect;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 日志切面
 * 记录访问url跟参数
 */
@Aspect
@Component
@Slf4j
public class HttpAspect {

    /**
     * 连接点，所有controller方法
     */
    @Pointcut("execution(public * com.gict.antifraudback.controller..*.*(..))")
    public void log() {

    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        StringBuffer url = request.getRequestURL();
        if (request.getQueryString() != null) {
            url.append("?").append(request.getQueryString());
        }
        Signature signature = joinPoint.getSignature();

        log.debug("Url={}", url);
        log.debug("Method={}", request.getMethod());
        log.debug("Controller={}", signature.getDeclaringTypeName() + "," + signature.getName());
        for (int i = 0; i < joinPoint.getArgs().length; i++) {
            log.debug("Parameter:" + (i + 1) + "=:" + joinPoint.getArgs()[i]);
        }
    }

    @AfterReturning(pointcut = "log()", returning = "object")
    public void doAfterReturing(Object object) {
        if (object != null) {
            log.debug("response={}", object.toString());
        }
    }
}
